<template>
  <div class="demo-test">
    <McHeader :logoImg="logoPng" :title="'HarmonyPilot'" class="headerIcon">
    </McHeader>
    <div v-if="startChat" ref="conversationRef" class="conversation-area">
      <template v-for="(msg, idx) in messages" :key="idx">
        <McBubble v-if="msg.from === 'user'" :content="msg.content" :align="'right'" :avatarConfig="msg.avatarConfig">
        </McBubble>
        <McBubble v-else :loading="msg.loading ?? false" :avatarConfig="msg.avatarConfig">
          <McMarkdownCard :content="msg.content" :theme="theme"></McMarkdownCard>
          <template #bottom>
            <div class="bubble-bottom-operations">
              <i class="icon-copy-new"></i>
              <i class="icon-like"></i>
              <i class="icon-dislike"></i>
            </div>
          </template>
        </McBubble>
      </template>
    </div>
    <div v-else class="welcome-page">
<McIntroduction :logo-img="logo2Png" title="HarmonyPilot" sub-title="Hi，欢迎使用 HarmonyPilot" :description="[
        'HarmonyPilot（鸿蒙领航员，简称“鸿派”）。',
        '是一个为鸿蒙开发者提供沉浸式AI使用体验的服务或者工具，',
        '提供代码生成、智能问答、测试辅助、代码检测等功能。',
        '并通过智能Agent，在应用、外设驱动、设备开发等领域，',
        '提供自主编排、工程生成、智能调测等能力，提升开发者的体验和效率。',
      ]" class="headerIcon2x"></McIntroduction>
    </div>
    <div class="new-convo-button">
      <div class="agent-knowledge">
        <d-dropdown :position="['top']" @toggle="(val) => (isAgentOpen = val)">
          <div class="agent-wrapper">
            <img :src="logoPng" />
            <span>{{ selectedAgent.label }}</span>
            <i class="icon-infrastructure"></i>
            <i :class="['icon-chevron-down-2', { 'is-open': isAgentOpen }]"></i>
          </div>
          <template #menu>
            <McList :data="agentList" @select="(val) => (selectedAgent = val)"></McList>
          </template>
        </d-dropdown>
      </div>
      <d-button icon="add" shape="circle" title="新建对话" size="sm" @click="onNewConvo" />
    </div>
    <div style="padding: 0 12px 12px 12px">
      <McInput :value="inputValue" :maxLength="2000" @change="(e) => (inputValue = e)" @submit="onSubmit">
        <template #extra>
          <div class="input-foot-wrapper">
            <div class="input-foot-left">
              <span v-for="(item, index) in inputFootIcons" :key="index" @click="() => onInputIconClick(item)">
                <i :class="item.icon"></i>
                {{ item.text }}
              </span>
              <span class="input-foot-dividing-line"></span>
              <span class="input-foot-maxlength">{{ inputValue.length }}/2000</span>
            </div>
            <div class="input-foot-right">
              <d-button icon="op-clearup" shape="round" :disabled="!inputValue" @click="inputValue = ''">清空输入</d-button>
            </div>
          </div>
        </template>
      </McInput>
    </div>
  </div>
</template>
  
  <script setup lang="ts">
  import { nextTick, onMounted, ref } from 'vue';
  import { ThemeServiceInit, devuiLightTheme, devuiDarkTheme } from 'devui-theme';
  import 'vue-devui/button/style.css';
  import OpenAI from 'openai';
  const deepseek = new OpenAI({  
  baseURL: 'https://api.deepseek.com/v1',  
  apiKey: 'sk-37addc2257584318ba5e300d38da7305', 
  dangerouslyAllowBrowser: true,
});  
const logoPng = ref(`${window.staticPath}src/image/Hi.svg`);
const logo2Png = ref(`${window.staticPath}src/image/Hi.svg`);
// 初始是 infinityTheme 无限主题
const themeService = ThemeServiceInit(
  {
    'ide-light': devuiLightTheme,
    'ide-dark': devuiDarkTheme,
  },
  'ide-dark'
);
// 可以动态切换成 galaxyTheme 追光主题
themeService.applyTheme(devuiDarkTheme);
const theme = ref('dark');
const isAgentOpen = ref(false);
const conversationRef = ref();
const startChat = ref(false);
const agentList = ref([
  { label: 'MateChat', value: 'matechat', active: true },
  { label: 'InsCode', value: 'inscode' },
]);
const selectedAgent = ref(agentList.value[0]);
const onNewConvo = () => {
  startChat.value = false;
  messages.value = [];
};
  const inputValue = ref('');
  const inputFootIcons = [
    { icon: 'icon-at', text: '智能体' },
    { icon: 'icon-standard', text: '词库' },
    { icon: 'icon-add', text: '附件' },
  ];
  const aiModelAvatar = {
  imgSrc: logoPng,
  width: 32,
  height: 32,
};
const customerAvatar = {
  imgSrc: 'https://matechat.gitcode.com/png/demo/userAvatar.svg',
  width: 32,
  height: 32,
};
const messages = ref([]);
  const onInputIconClick = (e) => {
  if (e.icon === 'icon-at') {
    inputValue.value += `@${selectedAgent.value.label}`;
  }
};
  const onSubmit = (evt) => {
  inputValue.value = '';
  if (!messages.value.length) {
    startChat.value = true;
  }
  // 用户发送消息
  messages.value.push({
    from: 'user',
    content: evt,
    avatarPosition: 'side-right',
    avatarConfig: { ...customerAvatar },
  });
  nextTick(() => {
    conversationRef.value?.scrollTo({
      top: conversationRef.value.scrollHeight,
      behavior: 'smooth',
    });
  });
  fetchData(evt);
};
const themeChange = () => {
  if (themeService) {
    theme.value = themeService.currentTheme.id === 'infinity-theme' ? 'light' : 'dark';
  }
}
onMounted(() => {
  themeChange();
  if (themeService && themeService.eventBus) {
    themeService.eventBus.add('themeChanged', themeChange);
  }
}); 

const fetchData = async (request) => {
  messages.value.push({
    from: 'ai-model',
    content: '',
    avatarPosition: 'side-left',
    avatarConfig: { ...aiModelAvatar },
    loading: true,
   });
  const completion = await deepseek.chat.completions.create({
    model: 'deepseek-chat', // 根据deepseek模型列表进行替换
    messages: [{role:'system', content: "你作为一个专业的代码专家，请回答用户的问题，以markdown的格式返回"},
     { role: 'user', content: request }],
    stream: true, // 为 true 则开启接口的流式返回
  });

  messages.value[messages.value.length - 1].loading = false;
  for await (const chunk of completion) {
    const content = chunk.choices[0]?.delta?.content || '';
    const chatId = chunk.id;
    messages.value[messages.value.length - 1].content += content;
    messages.value[messages.value.length - 1].id = chatId;
    nextTick(() => {
        conversationRef.value?.scrollTo({
          top: conversationRef.value.scrollHeight
        });
      });
  }
};
  </script>
  
  <style scoped>
  .demo-test {
    width: calc(100% - 40px);
    min-width: 500px;
    height: calc(100vh - 180px);
    display: flex;
    flex-direction: column;
    gap: 8px;
  
  
    width: calc(100% - 40px);
    /* margin: 20px auto; */
    height: calc(100vh - 40px);
    padding: 20px;
    gap: 8px;
    background: #303133;
    border: 1px solid #303133;
    border-radius: 16px;
  
  
  
    .conversation-area,
    .welcome-page {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: auto;
      padding: 0 12px;
    }
  
    .conversation-area {
      gap: 8px;
    }
  
    .welcome-page {
      gap: 24px;
      justify-content: center;
    }
  
    .guess-question {
      width: 100%;
      padding: 16px 12px;
      border-radius: var(--devui-border-radius-card);
      background-color: var(--devui-gray-form-control-bg);
  
      .guess-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: var(--devui-text);
        margin-bottom: 12px;
  
        &>div:first-child {
          font-weight: 700;
          font-size: var(--devui-font-size);
        }
  
        &>div:last-child {
          font-size: var(--devui-font-size-sm);
          cursor: pointer;
  
          span {
            margin-left: 4px;
          }
        }
      }
  
      .guess-content {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 8px;
  
        span {
          font-size: var(--devui-font-size-sm);
          color: var(--devui-text);
          padding: 4px 12px;
          border-radius: var(--devui-border-radius-full);
          background-color: var(--devui-gray-form-control-hover-bg);
          cursor: pointer;
        }
      }
    }
  
    .bubble-bottom-operations {
      margin-top: 8px;
  
      i {
        padding: 4px;
        border-radius: 4px;
        cursor: pointer;
  
        &:hover {
          background-color: var(--devui-icon-hover-bg);
        }
      }
    }
  
    .new-convo-button {
      padding: 0 12px;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      height: 39px;
      gap: 4px;
    }
  
    :deep(.simple-prompt .mc-list) {
      justify-content: unset;
    }
  
    :deep(.intro-prompt .mc-list) {
      justify-content: center;
    }
  
    .operations {
      i {
        padding: 4px;
        border-radius: 4px;
        cursor: pointer;
  
        &:hover {
          background: var(--devui-global-bg);
        }
      }
    }
  
    .agent-knowledge {
      flex: 1;
      display: flex;
      align-items: center;
  
      .agent-wrapper {
        display: flex;
        align-items: center;
        padding: 4px 8px;
        border-radius: var(--devui-border-radius-full);
        background-color: var(--devui-area);
        cursor: pointer;
  
        img {
          width: 16px;
          height: 16px;
          margin-right: 4px;
        }
  
        span {
          font-size: var(--devui-font-size);
          color: var(--devui-text);
          margin-right: 8px;
        }
  
        i {
          font-size: var(--devui-font-size);
          color: var(--devui-text);
          transition: transform 0.3s ease-in-out;
  
          &:last-child {
            margin-left: 4px;
          }
        }
  
        .is-open {
          transform: rotate(180deg);
        }
      }
  
      .agent-knowledge-dividing-line {
        width: 1px;
        height: 14px;
        margin: 0 12px;
        background-color: var(--devui-line);
      }
  
      .knowledge-wrapper {
        font-size: var(--devui-font-size);
        color: var(--devui-text);
        cursor: pointer;
  
        span {
          margin-left: 4px;
        }
      }
    }
  
    .input-foot-wrapper {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      height: 100%;
      margin-right: 8px;
  
      .input-foot-left {
        display: flex;
        align-items: center;
        gap: 8px;
  
        span {
          font-size: var(--devui-font-size-sm);
          color: var(--devui-text);
          cursor: pointer;
        }
  
        .input-foot-dividing-line {
          width: 1px;
          height: 14px;
          background-color: var(--devui-line);
        }
  
        .input-foot-maxlength {
          font-size: var(--devui-font-size-sm);
          color: var(--devui-aide-text);
        }
      }
  
      .input-foot-right {
        &>*:not(:first-child) {
          margin-left: 8px;
        }
      }
    }
  
    .headerIcon :deep(.mc-header-logo) {
      height: 32px;
      width: 32px;
    }
  
    :deep(.headerIcon2x) {
      img {
        height: 64px;
        width: 64px;
      }
    }
     
    
    
  }
  
  </style>